<template>
  <div class="app-container dialog-w80">
    <div class="customContainer">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-date-picker v-model="pickerDate" value-format="yyyy.MM.dd" type="daterange" align="right" unlink-panels range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="仓库" v-model="formInline.house_id">
            <el-option v-for="item in house_list" :key="item.house_id" :label="item.name" :value="item.house_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="订单状态:" v-model="formInline.status">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.order_no" placeholder="订单号查询" @keyup.enter.native="searchClick">
          </el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table highlight-current-row ref="multipleTable" :data="list" v-loading.body="listLoading" element-loading-text="Loading" border size="small"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="36"></el-table-column>
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status==0">待审核</span>
            <span v-if="scope.row.status==1">待发货</span>
            <span v-if="scope.row.status==2">待收货</span>
            <span v-if="scope.row.status==3">部分收货</span>
            <span v-if="scope.row.status==4">订单完结</span>
            <span v-if="scope.row.status==5">收货完成</span>
            <span v-if="scope.row.status==6">订单取消</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单编号">
          <template slot-scope="scope">
            <el-button @click="get_order_info(scope.row.id,scope.$index,scope.row.status,scope.row.house_out_name,scope.row.house_in_name)" type="text"
              size="small">{{scope.row.order_no}}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="调拨出库仓" prop="house_out_name"></el-table-column>
        <el-table-column align="center" label="调拨入库仓" prop="house_in_name"></el-table-column>
        <el-table-column align="center" label="下单时间" prop="create_time"></el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <span class="indexColor">{{!scope.row.remark?'---':scope.row.remark}}</span>
          </template>
        </el-table-column>
        <!-- 列表的操作按钮 -->
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button :disabled="scope.row.status!=0" @click="closeClick(scope.row.id,scope.row.status,scope.$index)" type="danger" size="mini">
              关闭订单</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹框 -->
    <el-dialog :close-on-click-modal="false" class="dialog_table" title="礼品调拨单审核" :visible.sync="detail_dialog">
      <div class="dialogInContainer" v-loading="dialogLoading">
        <div style="position:relative;top:-20px">调拨出库仓：{{house_out_name}}&#x3000;&#x3000;调拨入库仓：{{house_in_name}}
        </div>
        <el-table highlight-current-row :data="infolist" v-loading.body="listLoading" border size="small">
          <el-table-column align="center" label='序号' width="50">
            <template slot-scope="scope">
              <span class="indexColor">{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="图片" width="70">
            <template slot-scope="scope">
              <img :src="scope.row.thumb" width="50" height="50" alt="">
            </template>
          </el-table-column>
          <el-table-column align="center" label="礼品名称" prop="gift_name"></el-table-column>
          <el-table-column align="center" label="礼品编号" prop="gift_id"></el-table-column>
          <el-table-column align="center" label="箱规" prop="box_num"></el-table-column>
          <el-table-column align="center" label="尺寸">
            <template slot-scope="scope">
              {{scope.row.size?scope.row.size:'-'}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="三级分类" prop="type_name"></el-table-column>
          <el-table-column align="center" label="成本价" prop="money_cost"></el-table-column>
          <el-table-column align="center" label="订单数">
            <template slot-scope="scope">
              <el-input disabled type="number" onmousewheel="return false;" v-model="scope.row.order_num" placeholder="数量" @input="count"></el-input>
            </template>
          </el-table-column>
          <!-- 列表的操作按钮 -->
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-switch :disabled="isDisabled" active-value="0" inactive-value="1" v-model="scope.row.is_del"></el-switch>
            </template>
          </el-table-column>
        </el-table>
        <!-- 自定义底部 -->
        <br>
        <div class="bottom_box">
          <el-button class="pull-right" :disabled="isDisabled" size="small" type="primary" @click="saveClick()">确认提交</el-button>
          <p class="pull-right" style="line-height:0">礼品总数量:{{totalOrder}} 　礼品总金额:{{totalPrice|keepTwoNum}} 　
          </p>
        </div>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
      <el-button :disabled="exportForm.length==0" class="pull-right" type="primary" size="small" @click="exportClick()" :loading="exportLoading">调拨单导出
        <count-down ref="cd" />
      </el-button>
    </div>
  </div>
</template>
<script>
import { house, getList, getPage, order_info, save, close, getExport } from '@/api/goodsflow/allot_check';
import { pickerOptionsF, pickerDateF, optionMaxTime } from '@/utils';
export default {
  data() {
    return {
      exportLoading: false,
      dialogLoading: false,
      listLoading: false,
      status: [
        { id: 100, name: '全部' },
        { id: 0, name: '待审核' },
        { id: 1, name: '待发货' },
        { id: 2, name: '待收货' },
        { id: 3, name: '部分收货' },
        { id: 4, name: '订单完结' },
        { id: 5, name: '收货完成' },
        { id: 6, name: '订单取消' }
      ],
      formInline: {
        house_id: 0,
        order_no: '',
        start_time: '',
        end_time: '',
        status: 0,
        position: 'verify'
      },
      pickerOptions: pickerOptionsF(),
      pickerDate: pickerDateF(),
      house_list: null,
      list: [],
      totalDataNumber: 1,
      currentPage: 1,
      detail_dialog: false,
      infolist: [],
      switchVal: true,
      totalOrder: '0',
      totalPrice: '0',
      saveForm: {
        order_id: '',
        order: []
      },
      editIndex: '',
      isDisabled: false,
      exportForm: [],
      exportData: [],
      house_out_name: '',
      house_in_name: ''
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.house_list) {
        vm.gethouse();
        vm.searchClick();
      }
    });
  },
  methods: {
    gethouse() {
      house().then(response => {
        this.house_list = response;
      });
    },
    searchClick() {
      optionMaxTime(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.start_time = this.pickerDate ? this.pickerDate[0] : '';
        this.formInline.end_time = this.pickerDate ? this.pickerDate[1] : '';
        this.fetchData();
      });
    },
    // 关闭订单
    closeClick(id, status, index) {
      this.editIndex = index;
      this.$confirm('此操作为关闭, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        close({ order_id: id, status: status }).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.list[this.editIndex].status = 6;
          }
        });
      });
    },
    // 提交
    saveClick() {
      const that = this;
      that.saveForm.order = [];
      this.infolist.forEach(function(val, index) {
        if (val.order_num == '' || val.order_num == 0) {
          return;
        } else {
          that.saveForm.order.push({ look_money: val.money_cost, gift_id: val.gift_id, verify_num: val.order_num, is_del: val.is_del });
        }
      });
      if (this.saveForm.order.length == this.infolist.length) {
        this.$confirm('此操作提交, 是否继续?', '提示', { type: 'warning' }).then(() => {
          save(this.saveForm).then(response => {
            this.$message({
              type: response.code == 1 ? 'success' : 'error',
              message: response.message
            });
            if (response.code == 1) {
              this.list[this.editIndex].status = 1;
              this.detail_dialog = false;
              this.searchClick();
            }
          });
        });
      } else {
        that.$message({ type: 'error', message: '请将所有信息填写完整!' });
        return;
      }
    },
    // 打开订单详情
    get_order_info(id, index, status, house_out_name, house_in_name) {
      this.dialogLoading = true;
      this.house_out_name = house_out_name;
      this.house_in_name = house_in_name;
      this.isDisabled = status == 0 ? false : true;
      this.editIndex = index;
      this.saveForm.order_id = id;
      this.detail_dialog = true;
      order_info(id).then(response => {
        this.infolist = response;
        this.count();
        this.dialogLoading = false;
      });
    },
    // 计算
    count() {
      var totalPrice = 0; //临时总价
      var totalOrder = 0;
      this.infolist.forEach(function(val, index) {
        totalPrice += val.money_totle * 1; //累计总价
        totalOrder += val.order_num * 1;
      });
      this.totalPrice = parseFloat(totalPrice);
      this.totalOrder = parseFloat(totalOrder);
    },
    // 选择
    handleSelectionChange(val) {
      this.exportForm = val;
      console.log(this.exportForm);
    },
    // 导出按钮
    exportClick() {
      const idArr = [];
      this.exportForm.forEach(function(val, index) {
        idArr.push(val.id);
      });
      getExport({ order_id: idArr.join(',') }).then(response => {
        this.exportData = response;
        console.log(this.exportData);
        this.export2Excel();
      });
      this.exportLoading = true;
      this.$refs.cd.countDownF(30).then(() => {
        this.exportLoading = false;
      });
    },
    // 导出
    export2Excel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../vendor/Export2Excel');
        const tHeader = [
          '序号',
          '订单编号',
          '调拨出库仓',
          '调拨入库仓',
          '礼品名称',
          '礼品编号',
          '神采礼品编号',
          '礼品图片',
          '箱规',
          '一级分类',
          '二级分类',
          '三级分类',
          '订单数',
          '实际到货数',
          '到货货差'
        ]; //对应表格输出的title
        const filterVal = [
          'ID',
          'order_no',
          'house_out_name',
          'house_in_name',
          'gift_name',
          'id',
          'no_obsolete',
          'img',
          'box_num',
          'type_name_one',
          'type_name_second',
          'type_name',
          'order_num',
          'arrive_num',
          'last_arrive_num'
        ]; // 对应表格输出的数据
        const list = this.exportData;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '采购单'); //对应下载文件的名字
      });
    },
    // 导出
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then(response => {
          this.totalDataNumber = response * 20;
          getList(this.formInline).then(response => {
            this.list = response;
            this.listLoading = false;
          });
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then(response => {
        this.list = response;
        this.listLoading = false;
      });
    }
  }
};
</script>

<style>
.dialog-w80 .el-dialog {
  width: 80%;
}
</style>